from pyrogram.types import (InlineKeyboardMarkup, InlineKeyboardButton, 
                            CallbackQuery)
from pyrogram import Client
from plugins import state_handler
from utils.sql import db
from utils.logger import logger

# callback_data handler
@Client.on_callback_query()
async def callback_query_handler(client: Client, callback: CallbackQuery):
    data = str(callback.data).split("|")
    callback_function = data[0]
    user_id = callback.from_user.id
    chat_id = callback.message.chat.id
    if len(data) > 1:
        callback_data = data[1:]

    logger.info(f"user_id:{user_id} INLINE-button:{data}")
    
    # START REGISTRATION
    if callback_function == "registration":
        if db.isUserExist(user_id):
            message_text  = "💰 Давай заведу еще один счет!\n\n"
        else:
            message_text  = "💰 Для начала, я создам твой первый счет!\n\n"
            db.create_user(user_id)
        message_text += "Ты можешь дать ему имя, написав мне, или выбрать один из моих вариантов ☺️"

        await callback.edit_message_text(text=message_text,
            reply_markup=InlineKeyboardMarkup([[
            InlineKeyboardButton("Общий", callback_data=f"set-name|Общий"),
            InlineKeyboardButton("Безналичный", callback_data=f"set-name|Безналичный"),
            InlineKeyboardButton("Наличный", callback_data=f"set-name|Наличный")
            ]]))
            
        db.set_last_bot_message_id(user_id, callback.message.id)
        db.set_state(chat_id, "create_account wait_name")
        logger.debug(f"{callback_function}:SUCCESS")
    
    # SET NAME
    if callback_function == "set-name":
        await state_handler.create_account(client, callback.message, db.get_state(callback.from_user.id), callback=callback_data[0])
        logger.debug(f"{callback_function}:SUCCESS")
    # GET ABOUT
    if callback_function == "about":
        if db.isUserExist(user_id):
            reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("Меню", callback_data=f"menu")]])
        else:
            reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("Зарегистрироваться", callback_data=f"registration")]])
        await callback.edit_message_text(text="Мой создатель - @lolichga 😍\nЕсли возникнут какие-либо вопросы или предложения, то смело обращайся к нему! ☺\n\nТакже, мой исходный код открыт, его можно посмотреть в этом репозитории:\nnotabug.org/paralolik/shiro-wallet",
        reply_markup=reply_markup)
        logger.debug(f"{callback_function}:SUCCESS")

    # GET DEFAULT NAME ACCOUNNT
    if callback_function == "noname":
        db.create_account(chat_id, full_name="Общий")
        db.set_state(str(chat_id), 'set_balance:"Общий"')
        await callback.edit_message_text(text="☺️ Отлично! Новое имя счета - <b>Общий</b>\nА теперь введи начальный баланс. (напр. 1250.86)")
        logger.debug(f"{callback_function}:SUCCESS")

    # GET MENU
    if callback_function == "menu":
        reply_markup = InlineKeyboardMarkup([
            [InlineKeyboardButton("Состояние", callback_data=f"info"),
             InlineKeyboardButton("Транзакции", callback_data=f"transaction-get")],
            [InlineKeyboardButton("Новый счет", callback_data=f"registration"),
             InlineKeyboardButton("Редактировать счет", callback_data=f"account-edit-button")]
        ])
        await callback.edit_message_reply_markup(reply_markup=reply_markup)
        db.set_last_bot_message_id(user_id, callback.message.id)
        logger.debug(f"{callback_function}:SUCCESS")

    # GET ACCOUNTS INFO
    if callback_function == "info":
        accounts = db.get_user_accounts(user_id)
        text = "<b>💰 Состояние счетов:</b>\n\n"

        for account in accounts:
            transaction_ids = db.get_transaction_ids(account[0])
            full_name = account[2]
            balance = account[5]
            value_up = 0.0
            value_down = 0.0
            for transaction_id in transaction_ids:
                value = db.get_transaction_value(transaction_id)
                if value > 0:
                    value_up += value
                    spend_symbol = "+"
                else:
                    value_down += abs(value)
                    spend_symbol = ""
            if db.get_user_default_account_id(user_id) == account[0]:
                full_name = f"<b>{full_name}</b>"
            text += f"<u>{full_name}</u>: <b>{balance}₽</b>\n↓ <b>{value_down}₽</b> | ↑ <b>{value_up}₽</b>\n\n"
        
        await callback.edit_message_text(text=text, reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton("Меню", callback_data=f"menu")]]))
        logger.debug(f"{callback_function}:SUCCESS")

    # GET TRANSACTIONS INFO
    if callback_function == "transaction-get":
        accounts = db.get_user_accounts(user_id)
        text = ""
        for account in accounts:
            balance = account[5]
            account_name = account[2]
            transaction_ids = db.get_transaction_ids(account[0])
            text += f"<b>{account_name}:</b>\n"

            value_up = 0.0
            value_down = 0.0

            i = 0

            for transaction_id in transaction_ids:
                value = db.get_transaction_value(transaction_id)
                description = db.get_transaction_description(transaction_id)

                if value > 0:
                    value_up += value
                    spend_symbol = "+"
                else:
                    value_down += abs(value)
                    spend_symbol = ""
                i += 1
                text += f"{i}| <b>{spend_symbol}{value}₽</b> - <i>{description}</i>\n"
            text += f"<b>Текущий баланс: {balance}₽</b>\n↓ <b>-{value_down}₽</b> | ↑ <b>+{value_up}₽</b>\n\n"
        await callback.edit_message_text(text=text, reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton("Меню", callback_data=f"menu")]]))
        logger.debug(f"{callback_function}:SUCCESS")

    # APPROVE NEW TRANSACTION
    if callback_function == "t-a":
        account_id = callback_data[0]
        value = float(callback_data[1])
        description = callback_data[2]
        account_name = db.get_account_name(account_id)

        db.create_transaction(account_id, value, description)
        balance = db.get_account_balance(account_id)

        db.set_balance(account_id, balance + value)
        balance = db.get_account_balance(account_id)
        await callback.edit_message_text(text=f"☺️ Успешно добавила!\n\n<b>{account_name}: {balance}₽</b>", 
                reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("Меню", callback_data=f"menu")]]))
        logger.debug(f"{callback_function}:SUCCESS")

    # DELETE NEW TRANSACTION
    if callback_function == "transaction-delete":
        await callback.edit_message_text(text="💵 Жду новых записей!\nЕсли что, вот памятка:\n[Имя счета/алиас] [+-][Сумма] [Описание]\n\nЕсли не указать имя счета, то будет использован счет по умолчанию.",
                reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton("Состояние", callback_data=f"info"),
                        InlineKeyboardButton("Меню", callback_data=f"menu")]
                ]))
        logger.debug(f"{callback_function}:SUCCESS")
    
    # ACCOUNT EDIT BUTTON FROM MENU
    if callback_function == "account-edit-button":
        inline_accounts_list = list()
        accounts = db.get_user_accounts(user_id)
        accounts_count=0

        while accounts_count <= len(accounts):
            inline_accounts_list_include = list()
            for i in range(2):
                if accounts_count+i >= len(accounts):
                    break
                account = accounts[i+accounts_count]

                button = InlineKeyboardButton(text=account[2], callback_data=f"account-edit|{account[0]}")
                inline_accounts_list_include.append(button)
                
            accounts_count += 2
            inline_accounts_list.append(inline_accounts_list_include)
        inline_accounts_list.append([InlineKeyboardButton(text="Назад", callback_data=f"menu")])

        await callback.edit_message_text(text="☺️ Выбери счет, который желаешь изменить.",
                reply_markup=InlineKeyboardMarkup(inline_accounts_list))
        logger.debug(f"{callback_function}:SUCCESS")

    # ACCOUNT EDIT MENU
    if callback_function == "account-edit":
        account_id = callback_data[0]
        full_name = f"💰 Имя: <b>{db.get_account_name(account_id)}</b>"
        aliases = f"Алиасы: <b>{db.get_account_aliases(account_id)}</b>"

        transaction_ids = db.get_transaction_ids(account_id)
        value_up = 0.0
        value_down = 0.0
        for transaction_id in transaction_ids:
            value = db.get_transaction_value(transaction_id)
            if value > 0:
                value_up += value
                spend_symbol = "+"
            else:
                value_down += abs(value)
                spend_symbol = ""
        balance_value = db.get_account_balance(account_id)
        balanсe = f"Текущий баланс: <b>{balance_value}₽</b>"
        
        await callback.edit_message_text(text=f"{full_name}\n{aliases}\n{balanсe}",
                reply_markup = InlineKeyboardMarkup([
                    [InlineKeyboardButton("Имя", callback_data=f"account-edit-name|{account_id}"),
                     InlineKeyboardButton("Алиасы", callback_data=f"account-edit-aliases|{account_id}")],
                    [InlineKeyboardButton("Изменить баланс", callback_data=f"account-edit-balance|{account_id}"),
                     InlineKeyboardButton("Удалить", callback_data=f"account-delete|{account_id}")],
                    [InlineKeyboardButton("По умолчанию", callback_data=f"account-edit-default|{account_id}"),
                     InlineKeyboardButton("Назад", callback_data=f"account-edit-button")]
                ]))
        logger.debug(f"{callback_function}:SUCCESS")
    
    # ACCOUNT NAME EDIT
    if callback_function == "account-edit-name":
        account_id = callback_data[0]
        full_name = db.get_account_name(account_id)
        db.set_state(user_id, f"edit_account set_name:{account_id}")
        await callback.edit_message_text(text=f"Предыдущее имя: <b>{full_name}</b>\n\n☺️ Введи новое имя.")
        logger.debug(f"{callback_function}:SUCCESS")
    
    # ACCOUNT ALIASES EDIT
    if callback_function == "account-edit-aliases":
        account_id = callback_data[0]
        full_name = db.get_account_name(account_id)
        aliases = db.get_account_aliases(account_id)
        db.set_state(user_id, f"edit_account set_aliases:{account_id}")
        await callback.edit_message_text(text=f"<b>💰 {full_name}</b>\nТекущие алиасы: <b>{aliases}</b>\n\n<i>Алиасы - это короткие имена вашего счета.</i>\n\n<b>Введи новые алиасы через пробел.</b>")
        logger.debug(f"{callback_function}:SUCCESS")

    # EDIT ACCOUNT BALANCE
    if callback_function == "account-edit-balance":
        account_id = callback_data[0]
        full_name = db.get_account_name(account_id)
        balance = db.get_account_balance(account_id)
        db.set_state(user_id, f"edit_account set_balance:{account_id}")
        rofi = ""
        if balance <= 10000:
            rofl = "\n🧱 Пора на завод!"
        
        await callback.edit_message_text(text=f"<b>💰{full_name}</b>\nТекущий баланс: <b>{balance}</b>{rofl}\n\nВведи новый баланс.")
        logger.debug(f"{callback_function}:SUCCESS")

    # EDIT DEFAULT ACCOUNT
    if callback_function == "account-edit-default":
        account_id = callback_data[0]
        full_name = db.get_account_name(account_id)
        db.set_default_account_id(user_id, account_id)
        await callback.edit_message_text(text=f"☺️ Счет <b>{full_name}</b> выбран как счет по умолчанию!",
            reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton("Назад", callback_data=f"account-edit-button")]]))
        logger.debug(f"{callback_function}:SUCCESS")

    # INITIALIZE ACCOUNT DELETE
    if callback_function == "account-delete":
        account_id = callback_data[0]
        full_name = db.get_account_name(account_id)
        await callback.edit_message_text(text=f"Счет <b>{full_name}</b> будет удален. 😥 Вы уверены?",
            reply_markup = InlineKeyboardMarkup([
                [InlineKeyboardButton("Подтвердить", callback_data=f"account-delete-confirm|{account_id}"),
                 InlineKeyboardButton("Назад", callback_data=f"account-edit-button")]]))
        logger.debug(f"{callback_function}:SUCCESS")

    # CONFIRM ACCOUNT DELETE
    if callback_function == "account-delete-confirm":
        account_id = callback_data[0]
        full_name = db.get_account_name(account_id)
        db.delete_account(account_id)
        await callback.edit_message_text(text=f"🪦 Счет <b>{full_name}</b> удален, покойся с миром...",
            reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton("Назад", callback_data=f"account-edit-button")]]))
        logger.debug(f"{callback_function}:SUCCESS")
